<template>
  <div class="user-avatar">
    <a-avatar
      v-if="hasValidAvatar"
      :size="size"
      :image-url="processedAvatarUrl"
      @error="handleAvatarError"
      :style="{ backgroundColor: bgColor }"
      :key="avatarKey"
    />
    <a-avatar
      v-else
      :size="size"
      :style="{ backgroundColor: getAvatarColor(username) }"
    >
      {{ getAvatarText(username) }}
    </a-avatar>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';

// 组件属性定义
const props = defineProps({
  avatar: { type: String, default: '' },
  username: { type: String, default: 'User' },
  size: { type: [Number, String], default: 40 },
  bgColor: { type: String, default: '' }
});

// 头像加载错误状态
const avatarError = ref(false);

// 用于强制重新渲染的key
const avatarKey = ref(Date.now());

// 监听头像变化，更新key以强制重新渲染
watch(() => props.avatar, (newAvatar) => {
  if (newAvatar) {
    console.log('UserAvatar: 头像URL变化，强制刷新', newAvatar);
    avatarError.value = false;
    avatarKey.value = Date.now();
  }
});

// 头像更新事件处理函数
function handleAvatarUpdated(event) {
  console.log('UserAvatar: 收到头像更新事件', event.detail);
  avatarError.value = false;
  avatarKey.value = Date.now();
  
  // 强制刷新图片，绕过缓存
  setTimeout(() => {
    document.querySelectorAll('img[class*="arco-avatar-image"]').forEach(img => {
      if (img.src.includes(props.avatar?.split('?')[0] || '')) {
        console.log('UserAvatar: 强制刷新头像图片', img.src);
        // 添加随机参数以绕过缓存
        img.src = `${img.src.split('?')[0]}?t=${Date.now()}&r=${Math.random()}`;
      }
    });
  }, 100);
}

// 监听全局头像更新事件
onMounted(() => {
  window.addEventListener('avatar-updated', handleAvatarUpdated);
});

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('avatar-updated', handleAvatarUpdated);
});

// 判断是否有有效头像
const hasValidAvatar = computed(() => {
  const avatar = props.avatar;
  // 简化逻辑：无头像、空路径、默认头像或加载错误时使用文字头像
  if (!avatar || 
      avatar.trim() === '' || 
      avatar.includes('default-avatar') || 
      avatarError.value) {
    return false;
  }
  return true;
});

// 处理后的头像URL
const processedAvatarUrl = computed(() => {
  // 添加时间戳参数避免缓存问题
  const url = processAvatarUrl(props.avatar);
  const timestamp = avatarKey.value;
  const random = Math.random();
  return url.includes('?') 
    ? `${url}&t=${timestamp}&r=${random}` 
    : `${url}?t=${timestamp}&r=${random}`;
});

// 处理头像加载错误
function handleAvatarError() {
  avatarError.value = true;
}

// 处理头像URL - 简化版
function processAvatarUrl(url) {
  if (!url) return '';
  
  // 如果URL已是完整HTTP/HTTPS路径，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  
  // 获取基础URL并规范化
  const baseUrl = (import.meta.env.VITE_API_BASE_URL || '').replace(/\/+$/, '');
  
  // 清理URL：移除查询参数和API前缀，确保以/开头
  let cleanUrl = url.split('?')[0];
  cleanUrl = cleanUrl.replace(/^\/api\/v1/, '');
  cleanUrl = cleanUrl.startsWith('/') ? cleanUrl : '/' + cleanUrl;
  
  // 处理基础URL中可能存在的/api/v1后缀
  const finalBaseUrl = baseUrl.endsWith('/api/v1') 
    ? baseUrl.substring(0, baseUrl.length - 7) 
    : baseUrl;
    
  return finalBaseUrl + cleanUrl;
}

// 获取头像文字（首字母）
function getAvatarText(name) {
  if (!name) return 'U';
  return /[\u4e00-\u9fa5]/.test(name[0]) ? name[0] : name[0].toUpperCase();
}

// 根据用户名生成头像背景颜色
function getAvatarColor(username) {
  if (!username) return '#1890ff';
  
  const colors = [
    '#1890ff', '#52c41a', '#faad14', '#f5222d', 
    '#722ed1', '#eb2f96', '#fadb14', '#a0d911',
    '#13c2c2', '#fa8c16', '#9254de', '#006d75'
  ];
  
  // 简化哈希计算
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 5) - hash);
  }
  
  return colors[Math.abs(hash) % colors.length];
}
</script>

<style scoped>
.user-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style> 